<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="80px" class="searchform" inline>
        <el-form-item :label="$t('bs.externalNetworkRouting')" prop="url_map">
          <el-input
            v-model="listQuery.url_map"
            class="filter-item"
            placeholder="外网路由"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.internalNetworkRouting')" prop="url">
          <el-input
            v-model="listQuery.url"
            class="filter-item"
            placeholder="内网路由"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="中文名" prop="cn_name">
          <el-input
            v-model="listQuery.cn_name"
            class="filter-item"
            placeholder="中文名"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-button v-waves class="filter-item" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">
          {{ $t('table.add') }}
        </el-button>
      </el-form>

    </div>

    <div style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;">
      <div style="display: flex;flex-direction: row;padding-bottom: 24px">
        <div style="flex: 1;display: flex;align-items: center">
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleCreate"
          >
            {{$t('bs.batchDelete')}}
          </el-button>
        </div>
        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
          <el-popover
            v-model="tablesetvisible"
            placement="bottom-start"
            width="160"
          >
            <div class="setcheckbox">
              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
              <el-checkbox v-for="(item,key) in fileds" :key="key" v-model="item.is_show" false-label="0" true-label="1">
                {{ item.title }}
              </el-checkbox>
            </div>
            <div slot="reference" class="hoverbutton">
              <img src="/static/table/fiter.png">
              <span style="margin-left: 8px;color: #666666">筛选</span>
            </div>
          </el-popover>
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="序号" width="55">
          <template slot-scope="{$index,row}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column v-if="fileds.cn_name.is_show==1" :label="$t('bs.chineseName')">
          <template slot-scope="{row}">
            {{ row.cn_name }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.name.is_show==1" :label="$t('bs.applicationClassification')">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.url_map.is_show==1" :label="$t('bs.externalNetworkRouting')">
          <template slot-scope="{row}">
            {{ row.url_map }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.url.is_show==1" :label="$t('bs.internalNetworkRouting')">
          <template slot-scope="{row}">
            {{ row.url }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.method.is_show==1" :label="$t('bs.method')">
          <template slot-scope="{row}">
            {{ row.method }}
          </template>
        </el-table-column>

        <el-table-column v-if="fileds.is_token.is_show==1" label="是否检验token">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_token==1" type="warning">是</el-tag>
            <el-tag v-else type="success">否</el-tag>
          </template>
        </el-table-column>

        <el-table-column v-if="fileds.is_login.is_show==1" label="是否效验权限">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_login==1" type="warning">是</el-tag>
            <el-tag v-else type="success">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button circle icon="el-icon-edit" size="small" @click="handleUpdate(row)" />

            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @confirm="handleDelete(row,$index)"
            >
              <el-button slot="reference" style="margin-left: 8px" circle icon="el-icon-delete" size="small" />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page_no"
        :total="total"
        @pagination="getList"
      />

    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="中文名" prop="cn_name">
              <el-input v-model="temp.cn_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.method')" prop="method">
              <el-input v-model="temp.method" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="24">
            <el-form-item :label="$t('bs.externalNetworkRouting')" prop="url_map">
              <el-input v-model="temp.url_map" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('bs.internalNetworkRouting')" prop="url">
              <el-input v-model="temp.url" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="2">
          <el-col :span="24">
            <el-form-item :label="$t('bs.applicationClassification')" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item :label="$t('bs.tokenValidated')" prop="is_token">
              <el-switch
                v-model="temp.is_token"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.verifyUserPermissions')" prop="is_login">
              <el-switch
                v-model="temp.is_login"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="2">
          <el-col :span="24">
            <el-form-item :label="$t('bs.illustrate')" prop="memo">
              <el-input v-model="temp.memo" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('bs.additionalParameters')" prop="add_params">
          <el-input v-model="temp.add_params" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column label="Channel" prop="key" />
        <el-table-column label="Pv" prop="pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle, delArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      checked: true,
      tablesetvisible: false,

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      importanceOptions: ['CngP/MSE-TS1', 'CngP/MSE-TS2'],
      sortOptions: [{ label: '启用', key: '+id' }, { label: '禁用', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: '',
        add_params: '',
        cn_name: '',
        is_gettoken: '',
        is_login: '1',
        is_token: '1',
        is_user: '0',
        memo: '',
        method: '',
        name: '',
        url: '',
        url_map: ''
      },
      fileds: {
        cn_name: { filed: 'cn_name', title: '中文名称', is_show: '1' },
        name: { filed: 'name', title: '应用分类', is_show: '1' },
        url_map: { filed: 'url_map', title: '外网路由', is_show: '1' },
        url: { filed: 'url', title: '内网路由', is_show: '1' },
        method: { filed: 'method', title: '方法', is_show: '1' },
        is_token: { filed: 'is_token', title: '是否检验token', is_show: '1' },
        is_login: { filed: 'is_login', title: '是否效验权限', is_show: '1' }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: '此项不能为空', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: '此项不能为空', trigger: 'change' }],
        title: [{ required: true, message: '此项不能为空', trigger: 'blur' }]
      },
      downloadLoading: false

    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'routemap').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }

        this.listLoading = false
      })
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)
      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          queryParma['and'] = [
            { field: listkeys[i], operator: 'like', value: '%' + this.listQuery[listkeys[i]] + '%' }
          ]
        }
      }
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        add_params: '',
        cn_name: '',
        is_gettoken: '',
        is_login: '1',
        is_token: '1',
        is_user: '0',
        memo: '',
        method: '',
        name: '',
        url: '',
        url_map: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'route_map',
            add: this.temp
          }
          createArticle(data, 'routemap').then(() => {
            this.listQuery.where = {}
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'route_map',
            update: this.temp
          }
          updateArticle(data).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      delArticle({ id: [row.id].join(',') }, 'sl_route_map').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
}
</style>
